﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ScrumFactory.Composition.ViewModel;
using ScrumFactory.Composition;
using ScrumFactory.Services;
using System.ComponentModel;

namespace ScrumFactory.ProjectTeam.ViewModel {

    public class ProjectMembershipViewModel : BaseEditableObjectViewModel, IProjectMembershipViewModel, INotifyPropertyChanged {

        private IBackgroundExecutor executor;
        private ITeamService teamService;
        
        public ProjectMembershipViewModel(
            IBackgroundExecutor executor,
            ITeamService teamService,
            ProjectMembership membership, MemberProfile member, Role role) {

                this.executor = executor;
                this.teamService = teamService;

            ProjectMembership = membership;
            MemberProfile = member;
            Role = role;
        }

        public ProjectMembership ProjectMembership { get; private set; }
        public MemberProfile MemberProfile { get; private set; }
        public Role Role { get; private set; }

        public int? DayAllocation {
            get {
                return ProjectMembership.DayAllocation;
            }
            set {
                int? oldAllocation = ProjectMembership.DayAllocation;
                ProjectMembership.DayAllocation = value;
                executor.StartBackgroundTask(
                    () => { teamService.UpdateProjectMembership(ProjectMembership.MemberUId, ProjectMembership); },
                    () => { },
                    ex => {
                        ProjectMembership.DayAllocation = oldAllocation;
                        OnPropertyChanged("DayAllocation");
                    });
                OnPropertyChanged("DayAllocation");
            }
        }

        

        public void RefreshUI() {
            OnPropertyChanged("Role");
            OnPropertyChanged("MemberProfile");
            OnPropertyChanged("ProjectMembership");
            OnPropertyChanged("DayAllocation");
        }

    }
}
